/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JOptionPane;
import modelo.GestorArticulos;
import persistencia.AlmacenDAO;
import pojos.Almacen;
import pojos.Articulos;

/**
 *
 * @author David Rial
 */
public class DialogAddArticulos extends javax.swing.JDialog {

    /**
     * Creates new form DialogAddArticulos
     */
    
    AlmacenDAO almacenDAO = new AlmacenDAO();
    List<Almacen> alAlmacenes;
    
    public DialogAddArticulos(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setTitle("Añadir Articulo");
        alAlmacenes = almacenDAO.getAlmacenes();
        for (int i = 0; i < alAlmacenes.size(); i++) {
            jcbAlmacenes.addItem(alAlmacenes.get(i).getIdAlmacen());
        }
        //este evento añade un nuevo articulo en la base de datos en funcion de lo que hay en los textfields
        //tambien se mira si los campos numericos se introducen correctamente
        jbAdd.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                try{
                    if (!jtfDescripcion.getText().equals("") && !jtfPrecio.getText().equals("")) {
                        try{
                            insertaArticulos();
                            JOptionPane.showMessageDialog(jbAdd, "Se ha insertado el articulo.");
                            dispose();
                        }catch(NumberFormatException e){
                            JOptionPane.showMessageDialog(jbAdd, "Introduce un numero en el campo precio.");
                        }
                    }else 
                        JOptionPane.showMessageDialog(jbAdd, "Tienes que rellenar todos los campos.");
                }catch(Exception e){
                    JOptionPane.showMessageDialog(jbAdd, "Error al insertar el articulo.");
                    System.out.println("Error al insertar el articulo "+e);
                }
            }
        });
    }
    /**
     * Metodo al que se llama una vez verificado que todos los campos cumplen el formato correcto
     * Introduce un articulo en la base de datos
     */
    private void insertaArticulos(){
        GestorArticulos ga = new GestorArticulos();
        Almacen almacen;
        int idAlm = (int) jcbAlmacenes.getSelectedItem();
        ga.addArticulo(new Articulos(new Almacen(idAlm,"Almacen"+idAlm),jtfDescripcion.getText(),
            0,Integer.parseInt(jtfPrecio.getText())));
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jlIdalmacen = new javax.swing.JLabel();
        jcbAlmacenes = new javax.swing.JComboBox();
        jlDescripcion = new javax.swing.JLabel();
        jtfDescripcion = new javax.swing.JTextField();
        jlPrecio = new javax.swing.JLabel();
        jtfPrecio = new javax.swing.JTextField();
        jbAdd = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jlIdalmacen.setText("ID Almacen:");

        jlDescripcion.setText("Descripcion:");

        jlPrecio.setText("Precio:");

        jbAdd.setText("Añadir");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlIdalmacen, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jlDescripcion)
                            .addComponent(jlPrecio))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jcbAlmacenes, 0, 128, Short.MAX_VALUE)
                            .addComponent(jtfDescripcion)
                            .addComponent(jtfPrecio)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(96, 96, 96)
                        .addComponent(jbAdd)))
                .addContainerGap(19, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlIdalmacen, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jcbAlmacenes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(38, 38, 38)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlDescripcion)
                    .addComponent(jtfDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlPrecio)
                    .addComponent(jtfPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 49, Short.MAX_VALUE)
                .addComponent(jbAdd)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

//    /**
//     * @param args the command line arguments
//     */
//    public static void main(String args[]) {
//        /* Set the Nimbus look and feel */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
//         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(DialogAddArticulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(DialogAddArticulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(DialogAddArticulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(DialogAddArticulos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /* Create and display the dialog */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            public void run() {
//                DialogAddArticulos dialog = new DialogAddArticulos(new javax.swing.JFrame(), true);
//                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
//                    @Override
//                    public void windowClosing(java.awt.event.WindowEvent e) {
//                        System.exit(0);
//                    }
//                });
//                dialog.setVisible(true);
//            }
//        });
//    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jbAdd;
    private javax.swing.JComboBox jcbAlmacenes;
    private javax.swing.JLabel jlDescripcion;
    private javax.swing.JLabel jlIdalmacen;
    private javax.swing.JLabel jlPrecio;
    private javax.swing.JTextField jtfDescripcion;
    private javax.swing.JTextField jtfPrecio;
    // End of variables declaration//GEN-END:variables
}
